import type { Plugin } from 'vue'
import { useAuthorization } from '@/composables/app'
import { PageEnum } from '@/enums/common'
import { getWhiteList } from '@/utils/common'
import { Toast } from '@/utils/toast'

const whiteList = getWhiteList()

const interceptor = {
  invoke: ({ url }: UniApp.NavigateToOptions) => {
    const path = url.split('?')[0]

    console.log('route interceptor: url, path, whiteList', url, path, whiteList)

    if (!path.startsWith('/')) {
      // 处理相对路径
    }

    // 白名单直接放行
    if (whiteList.includes(path)) {
      return true
    }

    // 非白名单检查登录状态
    const token = useAuthorization()

    if (token.value && path === PageEnum.Login) {
      console.log('已登录，直接跳转首页')

      uni.switchTab({ url: PageEnum.Home })
      return false
    }

    if (token.value) {
      return true
    }

    const redirect = `${PageEnum.Login}?redirect=${encodeURIComponent(path)}`
    Toast.error('请先登录')
    uni.navigateTo({ url: redirect })
    return false
  },
}

export const routerInterceptor: Plugin = {
  install() {
    uni.addInterceptor('navigateTo', interceptor)
    uni.addInterceptor('redirectTo', interceptor)
    uni.addInterceptor('switchTab', interceptor)
    uni.addInterceptor('reLaunch', interceptor)
  },
}
